<template>
  <div>
    <Category :isShow="isShow" />
    <el-card
      shadow="hover"
      :body-style="{ padding: '20px' }"
      style="margin: 10px 0px; border: none"
    >
      <div v-show="sences == 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="!CategoryStore.c3Id"
          @click="addSpu"
          v-has="`btn.Spu.add`"
        >
          添加SPU
        </el-button>
        <!-- card body -->
        <el-table
          border
          style="margin: 10px 0px"
          :data="records"
          v-loading="loding"
          element-loading-text="Loding..."
          tooltip-effect="dark"
        >
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="spuName"
            label="SPU名称"
            align="center"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="description"
            label="SPU描述"
            show-overflow-tooltip
            align="center"
          ></el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template #default="{ row }">
              <el-button
                size="small"
                icon="Plus"
                title="新增SKU"
                plain
                @click="addSku(row)"
                v-has="`btn.Spu.addsku`"
              ></el-button>
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                title="修改SPU"
                @click="updateSpu(row)"
                v-has="`btn.Spu.update`"
              ></el-button>
              <el-button
                type="warning"
                size="small"
                icon="View"
                title="查看SKU列表"
                plain
                @click="dialogTable(row)"
                v-has="`btn.Spu.skus`"
              ></el-button>
              <el-popconfirm
                width="220"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon="InfoFilled"
                icon-color="#626AEF"
                :title="`确定要删除SPU${row.spuName}?`"
                @confirm="spuDelete(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                    v-has="`btn.Spu.delete`"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15]"
            background
            layout="prev,pager,next,jumper,->,sizes,total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <el-dialog :title="rowName + 'sku列表'" v-model="dialogVisable">
        <el-table :data="skuDialogData">
          <el-table-column label="sku名称" prop="skuName"></el-table-column>
          <el-table-column label="sku价格" prop="price"></el-table-column>
          <el-table-column label="sku重量" prop="weight"></el-table-column>
          <el-table-column label="sku图片">
            <template #default="{ row }">
              <el-image
                :src="row.skuDefaultImg"
                fit="fill"
                :lazy="true"
              ></el-image>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <skuForm ref="skuRef" v-show="sences == 1" @sen="changeSences"></skuForm>
      <spuForm ref="spuRef" v-show="sences == 2" @sen="changeSences"></spuForm>
    </el-card>
  </div>
</template>

<script lang="ts" setup name="index">
import type {
  SpuResponseData,
  Records,
  SpuList,
  skuValue,
} from '@/api/product/spu/type'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import useCategoryStore from '@/store/module/category'
import { getSpuList, lookSku, reqDeleteSpu } from '@/api/product/spu'
import { ElMessage } from 'element-plus'
import skuForm from './skuForm.vue'
import spuForm from './spuForm.vue'
let isShow = ref(false) //三级菜单组件是否禁用
let currentPage = ref<number>(1) //当前页码
let pageSize = ref<number>(5) //当前页展示多少条数据
let total = ref<number>(10) //一共多少条数据
let CategoryStore = useCategoryStore() //获取仓库读取c3id的值
let records = ref<Records>([]) //请求到的SPU列表属性值存在这里
let loding = ref(false) //加载遮罩
let sences = ref(0) //场景切换
let spuRef = ref<any>() //获取组件对外暴露的属性和方法
let skuRef = ref<any>() //获取组件对外暴露的属性和方法
//dialog组件的配置数据
let dialogVisable = ref(false)
let skuDialogData = ref<skuValue[]>([])
let rowName = ref('')
//获取到三级id的改变且不为空时请求数据
watch(
  () => CategoryStore.c3Id,
  (value) => {
    if (value) {
      getSpuData()
    }
  },
)
//页面加载三级id不为空时请求数据
onMounted(() => {
  if (CategoryStore.c3Id) {
    getSpuData()
  }
})
//定义请求数据函数
const getSpuData = async () => {
  loding.value = true
  let result: SpuResponseData = await getSpuList(
    currentPage.value,
    pageSize.value,
    CategoryStore.c3Id,
  )
  if (result.code == 200) {
    records.value = result.data.records
    currentPage.value = result.data.current
    pageSize.value = result.data.size
    total.value = result.data.total
    loding.value = false
  } else {
    loding.value = false
    ElMessage({ type: 'error', message: '数据格式错误' })
  }
}
//当每页显示多少条发生改变时，组件自带的事件会传每页显示多少条，然后重新请求数据就可以了
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getSpuData()
}
//当页码发生改变时，组件自带的事件会传页码，然后重新请求数据就可以了
const handleCurrentChange = (current: number) => {
  currentPage.value = current
  getSpuData()
}
//添加或修改成功后SPU场景切换回来(自定义事件)
let changeSences = (obj: any) => {
  // 场景切换
  sences.value = obj.flag
  //解除三级菜单禁用
  isShow.value = false
  //判断是添加还是修改，修改就在当前页，不是修改就跳到第一页
  if (obj.params == 'add') {
    currentPage.value = 1
  }
  //添加或修改成功后重新请求数据
  getSpuData()
}
//修改SPU场景切换
const updateSpu = (row: SpuList) => {
  sences.value = 2
  spuRef.value.onLoaded(row)
  isShow.value = true
}
//添加SPU场景切换
const addSpu = () => {
  sences.value = 2
  isShow.value = true
  // ref获取组件实例子组件暴露方法供父组件触发
  spuRef.value.addLoaded(CategoryStore.c3Id)
}
//查看sku列表对话框
const dialogTable = async (row: SpuList) => {
  rowName.value = row.spuName
  dialogVisable.value = true
  const result = await lookSku(row.id as number)
  if (result.code == 200) {
    skuDialogData.value = result.data
  } else ElMessage({ type: 'error', message: '暂无sku数据' })
}
//给spu添加sku
const addSku = (row: SpuList) => {
  const { c1Id, c2Id } = CategoryStore
  isShow.value = true
  sences.value = 1
  skuRef.value.initStart(c1Id, c2Id, row)
}
//删除spu
const spuDelete = async (spuId: number) => {
  await reqDeleteSpu(spuId)
    .then((result) => {
      if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getSpuData()
      } else ElMessage({ type: 'success', message: '删除失败' + result.code })
    })
    .catch((error) =>
      ElMessage({ type: 'success', message: '删除失败' + error }),
    )
}
//组件销毁清除数据
onBeforeUnmount(() => {
  useCategoryStore().$reset()
})
</script>
<style scoped lang="less"></style>
